import { http } from "@/utils/http";
import { baseUrlApi } from "./utils";
/** 检查一个变量是否为空 */
function isArrayNotEmpty(arr: any) {
  return Array.isArray(arr) && arr.length > 0;
}

/** 获取订单概览 */
export const getSummary = (timePeriod: Array<number>) => {
  return http.request<any>("get", baseUrlApi("order/rj/summary"), {
    /** 将13位时间戳转换成10位时间戳 */
    params: {
      starttime: timePeriod[0] / 1000,
      endtime: timePeriod[1] / 1000
    }
  });
};

/** 订单状态类型枚举 */
export enum OrderStatus {
  Unshipped = 1, // 未发货
  Shipped = 2, // 已发货
  Returned = 3, // 已回款
  NotReturned = 4 // 未回款
}
/** 获取订单列表参数 */
export type OrderListParams = {
  /** 结束时间 */
  endtime?: number;
  /** 页码 */
  page?: number;
  /** 数量 */
  size?: number;
  /** 开始时间 */
  starttime?: number;
  /** 订单状态 */
  typeid?: OrderStatus;
};

/** 获取订单列表 */
export const getOrderList = (data: OrderListParams) => {
  return http.request<any>("get", baseUrlApi("order/rj/orderlist"), {
    params: data
  });
};

/** 获取订单详情并重新组合数据
 * 1.判断 `productinfo` 和 `expendituredetails`是否为空
 *
 * 2.`productinfo` 不为空，遍历添加 `suppliers` 和 `purchaseprice` 字段
 *
 * 3.`expendituredetails` 不为空，遍历每项下的`productinfo`并添加对应的`suppliers` 和 `purchaseprice` 字段
 */
export async function getOrderDetail(orderId: string) {
  let res = await http.request<any>(
    "get",
    baseUrlApi(`order/rj/${orderId}`),
    {}
  );
  if (res.err.code === 0) {
    if (isArrayNotEmpty(res.data.productinfo)) {
      res.data.productinfo.forEach(item => {
        item.suppliername = "";
        item.purchaseprice = 0;
      });
    }
    const expenditureList = res.data.expenditure.list;
    if (isArrayNotEmpty(expenditureList)) {
      expenditureList.forEach(order => {
        order.productinfo.forEach(item => {
          item.suppliername = order.suppliername;
          item.purchaseprice = order.price;
          item.receiveSideFreight = order.receiveSideFreight;
          item.sendSideFreight = order.sendSideFreight;
          item.paymethod = order.paymethod;
        });
      });
      let tempList = res.data.productinfo.concat(
        ...expenditureList.map(item => item.productinfo)
      );
      // 按 fgoodsid 从大到小排序
      tempList.sort((a, b) => (b.fgoodsid || 0) - (a.fgoodsid || 0));
      res.data.productinfo = tempList;
    }
    return res;
  }
  return [];
}

/** 获取供应商列表 */
export function getSupplieList() {
  return http.request<any>("get", baseUrlApi("index/suppliername"), {});
}

/** 获取支付方式列表 */
export function getPaymentMethodList() {
  return http.request<any>("get", baseUrlApi("index/paymethod"), {});
}

/** 设置商品供货商信息 */
export function setGoodsSupplier(data: any) {
  const send_data = {
    fgoodsid: data["fgoodsids"].toString(),
    orderno: data["orderno"],
    paymethod: data["paymethod"],
    price: data["price"],
    receiveSideFreight: data["receiveSideFreight"],
    sendSideFreight: data["sendSideFreight"],
    suppliername: data["suppliername"]
  };

  return http.request<any>("post", baseUrlApi("order/rj/expenditure"), {
    data: send_data
  });
}

/** 获取历史物流公司列表 */
export function getDeliverList() {
  return http.request<any>("get", baseUrlApi("index/logisticscom"), {});
}

/** 获取所有物流公司信息 */
export function getAllDeliverList() {
  return http.request<any>("get", baseUrlApi("index/logisticscomlist"), {});
}

/** 设置订单物流信息 */
export function setOrderDeliver(rawData: any) {
  let data = {
    orderno: rawData.orderno,
    logisticsinfo: [
      {
        trackingnum: rawData.trackingnum,
        comcode: rawData.comcode,
        fgoodsids: rawData.fgoodsids,
        phone: rawData.phone
      }
    ]
  };
  return http.request<any>("post", baseUrlApi("order/rj/logistics"), { data });
}

/** 获取订单物流详情信息 */
export function getOrderDeliver(orderId: string, goodsid?: string) {
  return http.request<any>(
    "get",
    baseUrlApi(`order/rj/logistics/${orderId}/${goodsid}`)
  );
}

/** 获取全国各省份订单统计数据 */
export async function getProvincesSalesData(timePeriod: Array<number>) {
  let res = await http.request<any>(
    "get",
    baseUrlApi("statistics/regionalordervolume"),
    {
      /** 将13位时间戳转换成10位时间戳 */
      params: {
        starttime: timePeriod[0] / 1000,
        endtime: timePeriod[1] / 1000
      }
    }
  );

  let allProvices = [
    "南海诸岛",
    "北京",
    "天津",
    "上海",
    "重庆",
    "河北",
    "河南",
    "云南",
    "辽宁",
    "黑龙江",
    "湖南",
    "安徽",
    "山东",
    "新疆",
    "江苏",
    "浙江",
    "江西",
    "湖北",
    "广西",
    "甘肃",
    "山西",
    "内蒙古",
    "陕西",
    "吉林",
    "福建",
    "贵州",
    "广东",
    "青海",
    "西藏",
    "四川",
    "宁夏",
    "海南",
    "台湾",
    "香港",
    "澳门"
  ];

  let allCity = [
    "广州",
    "深圳",
    "佛山",
    "东莞",
    "中山",
    "珠海",
    "江门",
    "肇庆",
    "惠州",
    "汕头",
    "潮州",
    "揭阳",
    "汕尾",
    "湛江",
    "茂名",
    "阳江",
    "云浮",
    "韶关",
    "清远",
    "梅州",
    "河源"
  ];

  /**
   * @description: 创建默认数据
   * @param {*} arr 需要创建的数组
   * @return {*}
   */
  function createDefaultArray(arr) {
    return arr.map(item => {
      return {
        name: item,
        value: 0
      };
    });
  }

  /**
   * @description: 合并并降序数组
   * @param {*} arr1 旧数组
   * @param {*} arr2 新数组
   * @return {*}
   */
  function mergeArrays(arr1, arr2) {
    // 创建一个映射对象来存储合并后的结果
    const map = new Map();

    let newArr = [];
    // 遍历第一个数组，填充映射对象
    arr1.forEach(({ name, value }) => {
      map.set(name, value);
    });

    // 遍历第二个数组，更新映射对象中的值
    arr2.forEach(({ name, total: value }) => {
      map.set(name, value);
    });

    // 将映射对象转换为数组格式
    newArr = Array.from(map, ([name, value]) => ({ name, value }));

    // 按值降序排序
    return newArr.sort((a, b) => b.value - a.value);
  }

  /** 计算广东省总数并添加到全省 */
  let cityData = res.data.city;
  let gdSum = 0;
  cityData.forEach(item => {
    gdSum += item.total;
  });
  res.data.province.push({
    name: "广东",
    total: gdSum
  });

  res.data.province = mergeArrays(
    createDefaultArray(allProvices),
    res.data.province
  );

  res.data.city = mergeArrays(createDefaultArray(allCity), cityData);
  return res;
}

/** 获取供应商销售数据 */
export async function getSupplierSalesData(timePeriod: Array<number>) {
  return http.request<any>(
    "get",
    baseUrlApi("statistics/supplierexpenditure"),
    {
      /** 将13位时间戳转换成10位时间戳 */
      params: {
        starttime: timePeriod[0] / 1000,
        endtime: timePeriod[1] / 1000
      }
    }
  );
}

/** 获取采购单位排名 */
export async function getBuyerData(timePeriod: Array<number>) {
  return http.request<any>("get", baseUrlApi("statistics/unitprocurement"), {
    /** 将13位时间戳转换成10位时间戳 */
    params: {
      starttime: timePeriod[0] / 1000,
      endtime: timePeriod[1] / 1000
    }
  });
}

/** 获取品牌排名 */
export async function getBrandData(timePeriod: Array<number>) {
  return http.request<any>("get", baseUrlApi("statistics/probrand"), {
    /** 将13位时间戳转换成10位时间戳 */
    params: {
      starttime: timePeriod[0] / 1000,
      endtime: timePeriod[1] / 1000
    }
  });
}

/** 获取商品销量统计 */
export async function getProductData(timePeriod: Array<number>) {
  return http.request<any>("get", baseUrlApi("statistics/productsales"), {
    /** 将13位时间戳转换成10位时间戳 */
    params: {
      starttime: timePeriod[0] / 1000,
      endtime: timePeriod[1] / 1000
    }
  });
}

/** 获取订单状态统计 */
export async function getOrderStatus(orderID: string) {
  return http.request<any>("get", baseUrlApi(`order/rj/status/${orderID}`));
}

/** 获取订单状态列表参数 */
export type OrderStatusListParams = {
  /** 订单状态 */
  typeid?: number;
  /** 订单号 */
  orderno?: string;
  /** 采购单位 */
  purchasingunit?: string;
  /** 销售单位 */
  sellingunit?: string;
  /** 联系人 */
  contactsname?: string;
  /** 最小订单金额 */
  minprice?: number;
  /** 最大订单金额 */
  maxprice?: number;
  /** 结束时间 */
  endtime?: number;
  /** 页码 */
  page?: number;
  /** 数量 */
  size?: number;
  /** 开始时间 */
  starttime?: number;
};

/** 获取订单状态列表 */
export const getOrderStatusList = (data: OrderStatusListParams) => {
  return http.request<any>("post", baseUrlApi("order/rj/statuslist"), {
    data
  });
};
export const getOrderStatusList2 = (data: any) => {
  return http.request<any>("post", baseUrlApi("order/rj/statuslist2"), {
    data
  });
};

/** 更新订单状态 */
export const updateOrderStatus = (data: {
  orderno: string;
  status: string;
  note: string;
  salesman: string;
}) => {
  return http.request<any>("put", baseUrlApi(`order/rj/status`), {
    data
  });
};

/** 获取Excle文件 */
export const downloadExcel = (data?: any) => {
  return http.request<Blob>(
    "post",
    baseUrlApi("order/rj/export"),
    { data },
    { responseType: "blob" }
  );
};

/** 创建订单 */
export const createOrder = (data: any) => {
  return http.request<any>("post", baseUrlApi("order/rj/create"), {
    data
  });
};